import time
import requests
import json
import traceback
xmlForm ="""
	<xml>
	<ToUserName><![CDATA[%s]]></ToUserName>
	<FromUserName><![CDATA[%s]]></FromUserName>
	<CreateTime>%s</CreateTime>
	<MsgType><![CDATA[text]]></MsgType>
	<Content><![CDATA[%s]]></Content>
	</xml>
"""
def send_text(data):
    try:
        print('the data FROM users',data)
    	# %s 字符串占位符，数量要一致
    	# 响应用户消息时，要注意fromuser,touser的角色已互换，所以两个变量的次序要互换，任何错误都会导致无法响应用户消息
        url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg='+data['content']
    	# requests.get返回response对象，json方法可将response对象直接返回字典
        answer = requests.get(url)
        if answer.json()['result'] == 0 and answer.status_code == 200:
            reply = answer.json()['content']
        else:
            reply = '我很忙，请晚点再来找我'    
        response = xmlForm % (data['from'],data['to'],str(int(time.time())),reply)
        print('the data FOR user',response)
        print('Deal with the TEXT data from users successfully and send to wechat server')
        return response
    except Exception as e:
    # 导入traceback模块，打印更详细的异常信息，有利于调试程序
        traceback.print_exc()

def send_image(data):
    try:
        print('the data FROM users',data)
        picUrl = data['picUrl']
        api = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
        key = 'XMI4VdK5AX7KMYRO5Vn4cHhLhWC2hEHP'
        secret = 'w02WoqF40DlBjt31SvsUtI_jG3hokaLa'
        answer = requests.post(api,data={
            'api_key':key,
            'api_secret':secret,
            'image_url':picUrl,
            'return_attributes':'gender,beauty,emotion,age'
        })
        person = answer.json()['faces']
        print(person)
        if len(person) == 1:
            result = person[0]['attributes']
        # 获得一个带有情绪信息的字典，下面对情绪进行排序并获取置信度最高的情绪
            emotion =sorted(list(result['emotion'].items()),
                        key=lambda x:x[1],
                        reverse=True)[0:2]
            gender = result['gender']['value']
            age = result['age']['value']
            woman_score = result['beauty']['female_score']
            man_score = result['beauty']['male_score']
            if gender == 'Male':
                reply = '哇，图片上的男人好帅啊！可以看出这个男人带有{}与{}的情绪，女生会为他的颜值打{}分,男生会为他的颜值打{}分。我猜他应该有{}岁了吧。不知道我说得你认不认同。'.format(emotion[0][0],emotion[1][0],woman_score,man_score,age)
            elif gender == 'Female':
                reply = '哇，照片上的女人真漂亮！可以看出这个女人带有{}与{}的情绪，男生会为她的颜值打{}分，女生会为她的颜值打{}分。我猜她应该有{}岁了吧。不知道我说的你认不认同。'.format(emotion[0][0],emotion[1][0],man_score,woman_score,age)
        elif len(person) <= 5 and len(person) != 0:
            gender = []
            emotion = []
            mood = {}
            age = []
        # 获取人群中的每个人的性别、情绪
            for p in person:
                gender.append(p['attributes']['gender']['value'])
                age.append(p['attributes']['age']['value'])
                emotion.append(sorted(list(p['attributes']['emotion'].items()),
                                    key=lambda x:x[1],
                                    reverse=True)[0])
        # 对人群中的情绪进行统计
            for e in emotion:
                mood[e] = mood.get(e,0)+1
            feel = sorted(list(mood.items()),
                        key=lambda x:x[1],
                        reverse=True)[0][0]
            print('gender:',gender,'emotion:',emotion,'feel:',feel)
            rep = ''
            for n in range(len(person)):
                if gender[n] == 'Female':
                    sex = '女生'
                else:
                    sex = '男生'
                rep += '第{}位{}岁的{},带有{}的情绪。'.format(n+1,age[n],sex,emotion[n][0])
            begin = '哦，我知道了，照片当中有{}个人，其中'.format(len(person))
            reply = begin+rep
            '''   
            if gender.count('Male')>len(gender)/2:
                reply = '哇，图片上有好多人！男生居多,大家的心情都比较{}吧'.format(feel)
            elif gender.count('Male') == len(gender)/2:
                reply = '哦，照片当中男女人数相当，大家的心情都比较{}吧'.format(feel)
            else:
                reply = '哇，图片上有好多人！女生居多,大家的心情都比较{}吧'.format(feel)
            '''
        # 免费的key，官方至多能识别五个人的情绪，只好暂时这样了
        elif len(person) > 5:
            reply = '照片中有{}个人，超过了5个人了，我有密集恐惧症呀！放过我吧。'.format(len(person))
        # 没有返回结果，说明api没有检测到人脸，用户上传的很可能不是人像
        elif len(person) == 0:
        # 调用腾讯云的python SDK包来实现图像分析，贴标签的功能。
            from qcloud_image import Client
            from qcloud_image import CIUrl,CIFile,CIBuffer
            secretId = 'AKIDNZYP1wfFahaEdNf9PXR6YorgJlyH7Cn7'
            secretKey = 'JOYXA8uRjohN0nMhnflcEbomVyELGvLZ'
            appid = '1258704149'
            bucket = 'BUCKET'
            client = Client(appid,secretId,secretKey,bucket)
            client.use_https()
            qcloud = client.tag_detect(CIUrl(picUrl))
           # 如果code状态码不是0，就很有可能出现网络连接的问题。
            if qcloud['code'] == 0 :
                tags = qcloud['tags']
            # 用于储存所检测的物体名称
                tag_name = []
                for t in tags:
                    if t['tag_confidence'] > 15:
                        tag_name.append(t['tag_name'])
                body = ','.join(tag_name)
                reply = '这张图不错，里面有{}'.format(body)
            else:
                reply = '我很累，先睡一下……'
        print('发送关于图片的响应',reply)
        response = xmlForm % (data['from'],data['to'],str(int(time.time())),reply)
        return response
    except Exception as e:
        traceback.print_exc()

def send_voice(data):
    try:
        print('the data FROM users',data)
        data['content']=data['recognition']
        response = send_text(data)
        return response
    except Exception as e:
        traceback.print_exc()

def noType(data):
    try:
        print('the data FROM users',data)
        response = xmlForm % (data['from'],data['to'],str(int(time.time())),'该类型尚未开发，敬请期待吧！')
        print('the data FOR user',response)
        print('Deal with the TEXT data from users successfully and send to wechat server')
        return response
    except Exception as e:
        traceback.print_exc()

def busy(data):
    response = xmlForm % (data['from'],data['to'],str(int(time.time())),'我太累了，先去睡个觉，晚点再来找我玩，好吗？')
    return response
